//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal sealed class SupBookRecord : WorkbookLevelRecord
    {
        public SupBookRecord(AddIn addin)
        {
            _cch = 0x3A01;
        }
        private XLUnicodeString[] _tabNames = new XLUnicodeString[0];

        private ushort _tabCount;
        private ushort _cch;

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.SupBook; }
        }


        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            context.WriteUInt16(_tabCount);
            context.WriteUInt16(_cch);
            if (!IsSelfReferencing && !IsAddInReferencing)
                this.virtPath.Write(context.Writer);
            if (this._tabNames != null)
                foreach (var tabName in _tabNames)
                    tabName.Write(context);
        }
        public bool IsSelfReferencing { get { return _cch == 0x0401; }
        set
        {
            _cch = 0x401;

        }}
        public bool IsAddInReferencing { get { return _cch == 0x3A01; } }
        private XLUnicodeStringNoCch virtPath;
        public string VirtualPath{get { return (string) virtPath; }}

        public SupBookRecord()
        {
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
#if DEBUG
            var oldPosition = context.BaseStream.Position;
#endif
            context.PreviousSupBook = this;
            this._tabCount = context.ReadUInt16();
            this._cch = context.ReadUInt16();
            if (IsSelfReferencing || IsAddInReferencing)
            {
                ///  virtualPath
            }
            else
            {
                virtPath.Read(context.Reader, _cch);
 
            }
            string s = (string) virtPath;
            if (s != null && (s == " " || IsExternalWorkbookReferencing (s) ))
            {

                _tabNames = new XLUnicodeString[_tabCount];
                for (int i = 0; i < _tabNames.Length; i++)
                {
                    XLUnicodeString tabName = new XLUnicodeString();
                    tabName.Read(context.Reader);
                    _tabNames[i] = tabName;
                }
            }
#if DEBUG
            var newPosition = context.BaseStream.Position;
            Contract.Assert(newPosition - oldPosition == length);
#endif
        }

        private bool IsExternalWorkbookReferencing(string s)
        {
            Debug.WriteLine("not implemented is external workbook referencing")
                ;
            return true;
        }

        public override void Apply(BiffReaderWorkbookContext context)
        {
            if (this.IsSelfReferencing)
            {
                //context.ExternalWorkbooks.Add(context.Workbook);
                context.ExternalBookContexts.Add (new ExternalBookContext(context.Workbook));
                return;
            }
            var link = new ExternalLink(context.Workbook.ExternalLinks.Count);
            var externalWorkbook = new ExternalWorkbook(link, context.Workbook.Document);
            context.ExternalBookContexts.Add(new ExternalBookContext(externalWorkbook));
            link.ExternalBook = externalWorkbook;
            foreach (string name in _tabNames)
            {
                link.ExternalBook.SheetNames.Add(new ExternalSheetName {Value = name});
                link.ExternalBook.Sheets.Add(new ExternalSheet(link.ExternalBook, name));
               // externalWorkbook.Sheets.Add(new Worksheet(externalWorkbook, name));
            }
            context.Workbook.ExternalLinks.Add(link);
           // context.ExternalWorkbooks.Add(extWB);
        }

        private static string parseVirtualPath(string path)
        {
            path = path.Trim();
            if (path.StartsWith("\x0001\x0001@"))
            {
                path = path.Substring(3);
            }
            else if (path.StartsWith("\x0001\x0001"))
            {
                path = path.Substring(2, 1) + @":\" + path.Substring(3);
            }
            else if (path.StartsWith("\x0001\x0002"))
            {
                path = path.Substring(2);
            }
            else if (path.StartsWith("\x0001\x0005"))
            {
                path = path.Substring(3);
            }
            else if (path.StartsWith("\x0001\x0006"))
            {
                path = path.Substring(2);
            }
            else if (path.StartsWith("\x0001\a"))
            {
                path = path.Substring(2);
            }
            else if (path.StartsWith("\x0001\b"))
            {
                path = "file:///" + path.Substring(2);
            }
            else if (path.StartsWith("\x0001"))
            {
                path = path.Substring(1);
            }
            path = path.Replace('\x0003', '\\');
            return path;
        }
    }
}